package com.chen.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.chen.manager.mapper.CategoryMapper;
import com.chen.model.entity.product.Category;
import com.chen.model.vo.product.CategoryExcelVo;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class CategoryListener<T> extends AnalysisEventListener<T> {
    //  没有办法用自动注入的方式,获取mapper, 所以创建对象的时候手动
    //把参数带过来
    private CategoryMapper categoryMapper;
    public CategoryListener(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }
    /**
     * 每隔100条存储数据库,然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<CategoryExcelVo> CategoryList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(T data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        CategoryList.add((CategoryExcelVo) data);
        if (CategoryList.size() >= BATCH_COUNT) {
            //每保存到100条,执行一次mapper的插入方法
            saveData();
            CategoryList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 做兜底,如果最后没有100条数据了,也保证剩余的都保存的数据库中
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }
    /**
     * 存储到数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", CategoryList.size());
        log.info("存储数据库成功！");
        categoryMapper.insertExcelData(CategoryList);
    }
}
